//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by admin on 16/1/17.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    @objc private func close(){
      dismissViewControllerAnimated(true, completion: nil)

    }
    // 本地代码和js通讯
    @objc private func defaultAccount(){
        let jsString = "document.getElementById('userId').value = '646369274@qq.com',document.getElementById('passwd').value = 'WD-0713wd'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航条
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        // 上线前记得注销
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        // 加载页面
        loadOAuthPage()
       }

    // MARK :加载网页授权
    private func loadOAuthPage(){
      let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        if  let url = NSURL(string: urlString){
        
         let request = NSURLRequest(URL: url)
        
            // 使用webView加载页面
            webView.loadRequest(request)
        }
    }
 
}

// 使用extension  为当前类直接扩展协议方法
extension  OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        // 显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // 关闭
        SVProgressHUD.dismiss()
    }
    //  Bool 协议方法 返回值围殴bool
    // 如果返回true  持有协议对象 就可以正常工作 否则no
    /*
    // 请求授权页面  放过
     https://api.weibo.com/oauth2/authorize?client_id=2743805696&redirect_uri=http://www.itcast.cn
      //   注册相关的页面 屏蔽
    <NSMutableURLRequest: 0x7f8d6ba36d40> { URL: http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=4qfY2c&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2743805696%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D }
    <NSMutableURLRequest: 0x7f8d69443c70> { URL: http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=4qfY2c&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2743805696%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D }
    
       URL: https://api.weibo.com/oauth2/authorize }
    // 授权请求 code
    <NSMutableURLRequest: 0x7f8d69557980> { URL: https://api.weibo.com/oauth2/authorize# }
    <NSMutableURLRequest: 0x7f8d697579d0> { URL: https://api.weibo.com/oauth2/authorize }
    // 屏蔽
    <NSMutableURLRequest: 0x7f8d6b956200> { URL: http://www.itcast.cn/?code=a20d74252fb90136cc6c7d9694548f16 }
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //  js调用本地代码
        let urlString = request.URL?.absoluteString ?? ""
        
        // 屏蔽掉不希望加载的页面
        if urlString.hasPrefix("https://api.weibo.com/"){
        
            return true
        }
        
        if !urlString.hasPrefix("http://www.itcast.cn"){
            return false
        
        }
        
        // 程序如果走到这里就只有包含回调的的url才能运行到
        //  获取网络授权码
        guard let query = request.URL?.query else {
            // 获取不到参数列表
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
          // 获取到code码
          //  请求用户taken
         loadAccessToken(code)
         return false
    }
    
    // 请求用户的taken
    private func loadAccessToken(code:String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //  请求的参数需要拼装成字典格式
          let  parameters = ["client_id":client_id, "client_secret" :client_secret, "grant_type": "authorization_code", "code":code, "redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        // 添加反序列化类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters , success: { (_, result) -> Void in
                print(result)
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    
}

